#include "mainwindow.h"


MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
    // 获取数据库管理器的单例实例，而不是直接创建
    m_db = DatabaseManager::getInstance();

    // 初始化数据库（连接 SQLite，建立表）
    m_db->init("physio_data.sqlite");

    m_gsrDevice = new GSRDevice(this);
    m_eegDevice = new EEGDevice(this);
    m_ecgDevice = new ECGDevice(this);
    m_chartWidget = new ChartWidget(this);
    m_chatWidget = new ChatWidget(this);
    m_audioWidget = new AudioPlayerWidget(this);
    m_analysisWidget = new AnalysisWidget(this);
    //设备检测模块
    m_deviceMonitorPanel = new DeviceMonitorPanel(this);

    // 创建文字转语音管理器
    m_ttsManager = new TextToSpeechManager(this);

    // 创建被试信息采集对话框
    m_subjectInfoDialog = new SubjectInfoDialog(m_db, this);

    // 隐藏主窗口，先显示被试信息采集对话框
    hide();

    // 应用主题和样式表
    loadStyleSheet();
    applyTheme();

    setupUi();
    setupDockWidgets();
    connectSignals();
    setupDeviceMonitorConnections();

    // 状态栏显示准备状态
    statusBar()->showMessage("就绪");

    // 显示被试信息采集对话框
    QTimer::singleShot(100, this, &MainWindow::showSubjectInfoDialog);

    setupDeviceThreads();
}

MainWindow::~MainWindow() {
    // 停止线程
    if (m_ecgThread && m_ecgThread->isRunning()) {
        m_ecgThread->stopThread();
        m_ecgThread->wait();
    }
    // 停止GSR线程
    if (m_gsrThread && m_gsrThread->isRunning()) {
        m_gsrThread->stopThread();
        m_gsrThread->wait();
    }
}

void MainWindow::loadStyleSheet() {
    // 加载主样式表
    QFile file(":/styles/medical.qss");
    if (file.exists() && file.open(QFile::ReadOnly | QFile::Text)) {
        m_styleSheet = QLatin1String(file.readAll());
        file.close();
    } else {
        // 如果外部样式表不存在，使用内联样式
        m_styleSheet = R"(
            /* 全局样式 */
            QMainWindow, QDialog {
                background-color: #f0f5fa;
                color: #2c3e50;
            }

            /* 按钮样式 - 修改为默认透明背景，悬停时显示浅灰色 */
            QPushButton {
                background-color: transparent;
                color: #2c3e50;
                border: none;
                border-radius: 4px;
                padding: 6px 12px;
                font-weight: bold;
            }

            QPushButton:hover {
                background-color: #e0e0e0;
            }

            QPushButton:pressed {
                background-color: #cccccc;
            }

            QPushButton:disabled {
                color: #7f8c8d;
                background-color: transparent;
            }

            /* 工具栏 */
            QToolBar {
                background-color: #ecf0f1;
                border-bottom: 1px solid #bdc3c7;
                spacing: 5px;
                padding: 2px;
            }

            /* 分组框 */
            QGroupBox {
                border: 1px solid #bdc3c7;
                border-radius: 5px;
                margin-top: 1ex;
                font-weight: bold;
                background-color: rgba(255, 255, 255, 180);
            }

            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 0 5px;
                color: #2980b9;
            }

            /* 复选框 */
            QCheckBox {
                spacing: 8px;
            }

            QCheckBox::indicator {
                width: 16px;
                height: 16px;
            }

            /* 状态栏 */
            QStatusBar {
                background-color: #ecf0f1;
                color: #2c3e50;
            }

            /* 标签 */
            QLabel#currentSubjectLabel {
                font-weight: bold;
                color: #2980b9;
                font-size: 12pt;
                padding: 5px;
                background-color: rgba(236, 240, 241, 150);
                border-radius: 4px;
            }

            /* 进度条 */
            QProgressBar {
                border: 1px solid #bdc3c7;
                border-radius: 3px;
                text-align: center;
                background-color: #ecf0f1;
            }

            QProgressBar::chunk {
                background-color: #3498db;
                width: 10px;
                margin: 0.5px;
            }

            /* Dock窗口 */
            QDockWidget {
                titlebar-close-icon: url(:/icons/close.png);
                titlebar-normal-icon: url(:/icons/undock.png);
            }

            QDockWidget::title {
                text-align: center;
                background-color: #3498db;
                color: white;
                padding: 5px;
            }

            /* 列表和表格 */
            QListWidget, QTableView {
                border: 1px solid #bdc3c7;
                border-radius: 3px;
                alternate-background-color: #ecf0f1;
            }

            QListWidget::item:selected, QTableView::item:selected {
                background-color: #3498db;
                color: white;
            }

            /* 菜单样式 */
            QMenu {
                background-color: white;
                border: 1px solid #bdc3c7;
                border-radius: 3px;
            }

            QMenu::item {
                padding: 5px 25px 5px 30px;
                border: 1px solid transparent;
            }

            QMenu::item:selected {
                background-color: #e0e0e0;
                color: #2c3e50;
            }
        )";
    }

    qApp->setStyleSheet(m_styleSheet);
}

void MainWindow::applyTheme() {
    // 应用现代化主题
    qApp->setStyle(QStyleFactory::create("Fusion"));

    // 设置应用程序调色板
    QPalette palette;
    palette.setColor(QPalette::Window, QColor(240, 245, 250));
    palette.setColor(QPalette::WindowText, QColor(44, 62, 80));
    palette.setColor(QPalette::Base, QColor(255, 255, 255));
    palette.setColor(QPalette::AlternateBase, QColor(236, 240, 241));
    palette.setColor(QPalette::ToolTipBase, QColor(255, 255, 255));
    palette.setColor(QPalette::ToolTipText, QColor(44, 62, 80));
    palette.setColor(QPalette::Text, QColor(44, 62, 80));
    palette.setColor(QPalette::Button, QColor(236, 240, 241));
    palette.setColor(QPalette::ButtonText, QColor(44, 62, 80));
    palette.setColor(QPalette::Link, QColor(41, 128, 185));
    palette.setColor(QPalette::Highlight, QColor(52, 152, 219));
    palette.setColor(QPalette::HighlightedText, QColor(255, 255, 255));

    qApp->setPalette(palette);
}

void MainWindow::setupUi() {
    // 设置窗口标题和大小
    setWindowTitle("脑健康监测系统");
    resize(2000, 1200);
    setWindowIcon(QIcon(":/icons/brain.png"));

    // 创建中央窗口部件
    QWidget *centralWidget = new QWidget(this);
    centralWidget->setObjectName("centralWidget");
    setCentralWidget(centralWidget);

    // 创建主布局 - 使用水平布局
    QHBoxLayout *mainLayout = new QHBoxLayout(centralWidget);
    mainLayout->setContentsMargins(8, 8, 8, 8);
    mainLayout->setSpacing(8);

    // 创建左侧垂直布局面板
    QVBoxLayout *leftPanelLayout = new QVBoxLayout();
    leftPanelLayout->setSpacing(10);
    leftPanelLayout->setContentsMargins(5, 10, 5, 10);

    // 1. 添加logo到左侧最上方 - 调整尺寸和样式，确保可见
    QLabel *logoLabel = new QLabel(this);
    // 确保使用正确的路径加载logo图片
    QPixmap logoPixmap("D:/lucy/QT6/1.1.1/resources/logo.png");

    if (logoPixmap.isNull()) {
        // 如果无法加载图片，创建一个文本logo
        logoLabel->setText("脑健康监测系统");
        logoLabel->setStyleSheet("QLabel { font-size: 16px; font-weight: bold; color: #2980b9; }");
    } else {
        // 放大logo并确保其可见
        logoLabel->setPixmap(logoPixmap.scaled(80, 80, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    }
    logoLabel->setAlignment(Qt::AlignCenter);
    logoLabel->setMinimumHeight(90);
    logoLabel->setStyleSheet("QLabel { margin-bottom: 10px; background-color: transparent; }");
    leftPanelLayout->addWidget(logoLabel);

    // 添加一个分隔线
    QFrame *line = new QFrame(this);
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);
    line->setStyleSheet("QFrame { color: #cccccc; }");
    leftPanelLayout->addWidget(line);

    // 2. 添加按钮到左侧logo下方 - 统一按钮样式和大小
    // 自定义按钮样式 - 默认无背景，悬停时显示浅灰色背景
    QString buttonStyle = R"(
        QPushButton {
            text-align: left;
            padding: 8px 12px;
            border: none;
            border-radius: 4px;
            background-color: transparent;
            min-height: 36px;
            min-width: 150px;
            font-family: "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
            font-size: 14px;
        }
        QPushButton:hover {
            background-color: #e0e0e0;
        }
        QPushButton:pressed {
            background-color: #cccccc;
        }
    )";

    // 新增被试按钮
    m_newSubjectButton = new QPushButton("新增被试", this);
    m_newSubjectButton->setIcon(QIcon(":/icons/add_user.png"));
    m_newSubjectButton->setObjectName("newSubjectButton");
    m_newSubjectButton->setStyleSheet(buttonStyle);
    leftPanelLayout->addWidget(m_newSubjectButton);

    // 开始采集按钮
    m_startAcquisitionButton = new QPushButton("开始采集", this);
    m_startAcquisitionButton->setObjectName("startAcquisitionButton");
    m_startAcquisitionButton->setIcon(QIcon(":/icons/start.png"));
    m_startAcquisitionButton->setStyleSheet(buttonStyle);
    leftPanelLayout->addWidget(m_startAcquisitionButton);

    // 停止采集按钮
    m_stopAcquisitionButton = new QPushButton("停止采集", this);
    m_stopAcquisitionButton->setObjectName("stopAcquisitionButton");
    m_stopAcquisitionButton->setIcon(QIcon(":/icons/stop.png"));
    m_stopAcquisitionButton->setStyleSheet(buttonStyle);
    leftPanelLayout->addWidget(m_stopAcquisitionButton);

    // 开始刺激按钮
    m_startStimulusButton = new QPushButton("开始刺激", this);
    m_startStimulusButton->setObjectName("startStimulusButton");
    m_startStimulusButton->setIcon(QIcon(":/icons/stimulus_start.png"));
    m_startStimulusButton->setStyleSheet(buttonStyle);
    leftPanelLayout->addWidget(m_startStimulusButton);

    // 停止刺激按钮
    m_stopStimulusButton = new QPushButton("停止刺激", this);
    m_stopStimulusButton->setObjectName("stopStimulusButton");
    m_stopStimulusButton->setIcon(QIcon(":/icons/stimulus_stop.png"));
    m_stopStimulusButton->setStyleSheet(buttonStyle);
    m_stopStimulusButton->setEnabled(false); // 初始状态禁用
    leftPanelLayout->addWidget(m_stopStimulusButton);

    // 生成报告按钮
    QPushButton *generateReportButton = new QPushButton("生成报告", this);
    generateReportButton->setObjectName("generateReportButton");
    generateReportButton->setIcon(QIcon(":/icons/report.png"));
    generateReportButton->setStyleSheet(buttonStyle);
    leftPanelLayout->addWidget(generateReportButton);
    // 添加对话干预设置到设置菜单 - 与其他设置项保持一致的样式
    QPushButton *chatDialogButton = new QPushButton("智能对话", this);
    chatDialogButton->setObjectName("chatDialogButton");
    chatDialogButton->setIcon(QIcon(":/icons/chat.png"));
    chatDialogButton->setStyleSheet(buttonStyle);
    leftPanelLayout->addWidget(chatDialogButton);

    // 连接智能对话按钮点击信号
    connect(chatDialogButton, &QPushButton::clicked, this, &MainWindow::showChatDialog);

    // 添加设置按钮 - 确保与其他按钮大小一致
    QPushButton *settingsButton = new QPushButton("设置", this);
    settingsButton->setObjectName("settingsButton");
    settingsButton->setIcon(QIcon(":/icons/settings.png"));
    settingsButton->setStyleSheet(buttonStyle);
    leftPanelLayout->addWidget(settingsButton);

    // 添加另一个分隔线
    QFrame *line2 = new QFrame(this);
    line2->setFrameShape(QFrame::HLine);
    line2->setFrameShadow(QFrame::Sunken);
    line2->setStyleSheet("QFrame { color: #cccccc; margin-top: 5px; margin-bottom: 5px; }");
    leftPanelLayout->addWidget(line2);

    // 3. 添加当前被试标签到左侧
    m_currentSubjectLabel = new QLabel("当前被试：无", this);
    m_currentSubjectLabel->setObjectName("currentSubjectLabel");
    m_currentSubjectLabel->setMinimumWidth(150);
    m_currentSubjectLabel->setAlignment(Qt::AlignCenter);
    m_currentSubjectLabel->setStyleSheet("QLabel { font-family: \"Microsoft YaHei\", \"微软雅黑\", Arial, sans-serif; font-size: 14px; }");
    leftPanelLayout->addWidget(m_currentSubjectLabel);

    // 添加刺激进度条
    QFont standardFont("Microsoft YaHei", 10);

    // 创建进度条
    m_stimulusProgressBar = new QProgressBar(this);
    m_stimulusProgressBar->setRange(0, 100);
    m_stimulusProgressBar->setValue(0);
    m_stimulusProgressBar->setTextVisible(true);
    m_stimulusProgressBar->setFormat("未刺激");  // 初始状态显示"未刺激"
    m_stimulusProgressBar->setFont(standardFont);

    // 直接将进度条添加到左侧面板
    leftPanelLayout->addWidget(m_stimulusProgressBar);

    // 4. 添加设备监控面板到左侧按钮下方
    leftPanelLayout->addWidget(m_deviceMonitorPanel);

    // 添加弹性空间，确保所有元素都向上对齐
    leftPanelLayout->addStretch(1);

    // 将左侧面板添加到主布局
    mainLayout->addLayout(leftPanelLayout);

    // 添加图表窗口到主布局的右侧
    mainLayout->addWidget(m_chartWidget, 4); // 给图表更多空间

    // 初始状态：停止按钮禁用
    m_stopAcquisitionButton->setEnabled(false);

    // 创建设置菜单
    QMenu *settingsMenu = new QMenu(this);
    settingsMenu->setStyleSheet("QMenu { font-family: \"Microsoft YaHei\", \"微软雅黑\", Arial, sans-serif; font-size: 14px; }");

    // 修改设备选择菜单项名称
    m_eegCheckBox = new QCheckBox("EEG设备", this);
    m_ecgCheckBox = new QCheckBox("ECG设备", this);
    m_gsrCheckBox = new QCheckBox("GSR设备", this);

    // 统一复选框字体
    QString checkBoxStyle = "QCheckBox { font-family: \"Microsoft YaHei\", \"微软雅黑\", Arial, sans-serif; font-size: 14px; }";
    m_eegCheckBox->setStyleSheet(checkBoxStyle);
    m_ecgCheckBox->setStyleSheet(checkBoxStyle);
    m_gsrCheckBox->setStyleSheet(checkBoxStyle);

    QWidgetAction *eegAction = new QWidgetAction(this);
    eegAction->setDefaultWidget(m_eegCheckBox);
    QWidgetAction *ecgAction = new QWidgetAction(this);
    ecgAction->setDefaultWidget(m_ecgCheckBox);
    QWidgetAction *gsrAction = new QWidgetAction(this);
    gsrAction->setDefaultWidget(m_gsrCheckBox);

    // 直接添加到设置菜单，不使用子菜单
    settingsMenu->addAction(eegAction);
    settingsMenu->addAction(ecgAction);
    settingsMenu->addAction(gsrAction);

    // 添加分隔符
    settingsMenu->addSeparator();

    // 添加选择被试按钮到设置菜单 - 不设置颜色
    m_selectSubjectButton = new QPushButton("选择被试", this);
    m_selectSubjectButton->setIcon(QIcon(":/icons/select_user.png"));
    m_selectSubjectButton->setObjectName("selectSubjectButton");
    m_selectSubjectButton->setStyleSheet(buttonStyle);
    QWidgetAction *selectSubjectAction = new QWidgetAction(this);
    selectSubjectAction->setDefaultWidget(m_selectSubjectButton);
    settingsMenu->addAction(selectSubjectAction);

    // 添加连接设备按钮到设置菜单 - 不设置颜色
    m_connectButton = new QPushButton("连接设备", this);
    m_connectButton->setObjectName("connectButton");
    m_connectButton->setIcon(QIcon(":/icons/connect.png"));
    m_connectButton->setStyleSheet(buttonStyle);
    QWidgetAction *connectAction = new QWidgetAction(this);
    connectAction->setDefaultWidget(m_connectButton);
    settingsMenu->addAction(connectAction);

    // 添加断开设备按钮到设置菜单
    m_disconnectButton = new QPushButton("断开设备", this);
    m_disconnectButton->setObjectName("disconnectButton");
    m_disconnectButton->setIcon(QIcon(":/icons/disconnect.png"));
    m_disconnectButton->setEnabled(false);
    m_disconnectButton->setStyleSheet(buttonStyle);
    QWidgetAction *disconnectAction = new QWidgetAction(this);
    disconnectAction->setDefaultWidget(m_disconnectButton);
    settingsMenu->addAction(disconnectAction);

    // 添加分隔符
    settingsMenu->addSeparator();

    // 添加音频刺激设置到设置菜单 - 修改为与其他设置项一致的样式
    QPushButton *audioSettingsButton = new QPushButton("音频刺激设置", this);
    audioSettingsButton->setIcon(QIcon(":/icons/audio_settings.png"));
    audioSettingsButton->setStyleSheet(buttonStyle);
    QWidgetAction *audioSettingsAction = new QWidgetAction(this);
    audioSettingsAction->setDefaultWidget(audioSettingsButton);
    settingsMenu->addAction(audioSettingsAction);
    connect(audioSettingsButton, &QPushButton::clicked, this, &MainWindow::showAudioSettings);

    // 添加算法分析设置到设置菜单 - 修改为与其他设置项一致的样式
    QPushButton *analysisSettingsButton = new QPushButton("算法分析设置", this);
    analysisSettingsButton->setIcon(QIcon(":/icons/analysis_settings.png"));
    analysisSettingsButton->setStyleSheet(buttonStyle);
    QWidgetAction *analysisSettingsAction = new QWidgetAction(this);
    analysisSettingsAction->setDefaultWidget(analysisSettingsButton);
    settingsMenu->addAction(analysisSettingsAction);
    connect(analysisSettingsButton, &QPushButton::clicked, this, &MainWindow::showAnalysisSettings);

    // 添加分隔符
    settingsMenu->addSeparator();

    // 添加CSV处理按钮到设置菜单 - 不设置颜色
    m_processCSVButton = new QPushButton("处理CSV文件", this);
    m_processCSVButton->setObjectName("processCSVButton");
    m_processCSVButton->setIcon(QIcon(":/icons/csv.png"));
    m_processCSVButton->setStyleSheet(buttonStyle);
    QWidgetAction *processCSVAction = new QWidgetAction(this);
    processCSVAction->setDefaultWidget(m_processCSVButton);
    settingsMenu->addAction(processCSVAction);

    // 关联设置按钮和设置菜单
    settingsButton->setMenu(settingsMenu);

    // 连接按钮到AudioPlayerWidget的方法
    connect(m_startStimulusButton, &QPushButton::clicked,
            m_audioWidget, &AudioPlayerWidget::onStartStimulus);
    connect(m_stopStimulusButton, &QPushButton::clicked,
            m_audioWidget, &AudioPlayerWidget::onStopStimulus);

    // 连接生成报告按钮信号
    connect(generateReportButton, &QPushButton::clicked, this, [this]() {
        // 调用分析模块生成报告
        if (m_analysisWidget) {
            m_analysisWidget->generateReport();
        }
    });

    // 在设置菜单中添加GSR采样率选择
    QMenu *gsrSamplingRateMenu = new QMenu("GSR采样率", this);
    gsrSamplingRateMenu->setStyleSheet("QMenu { font-family: \"Microsoft YaHei\", \"微软雅黑\", Arial, sans-serif; font-size: 14px; }");

    // 添加采样率选项
    QStringList samplingRates = GSRDevice::getAvailableSamplingRates();
    QActionGroup *samplingRateGroup = new QActionGroup(this);
    samplingRateGroup->setExclusive(true);

    for (const QString &rate : samplingRates) {
        QAction *action = new QAction(rate, this);
        action->setCheckable(true);
        if (rate == "100 Hz") {
            action->setChecked(true); // 默认选中100Hz
        }
        samplingRateGroup->addAction(action);
        gsrSamplingRateMenu->addAction(action);
    }

    // 添加GSR采样率菜单到设置菜单
    settingsMenu->addSeparator();
    settingsMenu->addMenu(gsrSamplingRateMenu);

    // 连接采样率选择信号
    connect(samplingRateGroup, &QActionGroup::triggered, this, &MainWindow::onGSRSamplingRateChanged);
}

void MainWindow::setupDockWidgets() {
    // 创建其他 Dock 窗口
    QDockWidget *audioDock = new QDockWidget("音频刺激", this);
    audioDock->setObjectName("audioDock");
    audioDock->setWidget(m_audioWidget);
    audioDock->setStyleSheet("QDockWidget::title { background-color: #3498db; color: white; text-align: center; }");

    QDockWidget *analysisDock = new QDockWidget("算法分析", this);
    analysisDock->setObjectName("analysisDock");
    analysisDock->setWidget(m_analysisWidget);
    analysisDock->setStyleSheet("QDockWidget::title { background-color: #2ecc71; color: white; text-align: center; }");

    QDockWidget *chatDock = new QDockWidget("智能对话", this);
    chatDock->setObjectName("chatDock");
    chatDock->setWidget(m_chatWidget);
    chatDock->setStyleSheet("QDockWidget::title { background-color: #9b59b6; color: white; text-align: center; }");

    // 将右侧 Dock 窗口按照要求从上到下排列：音频刺激、算法分析、智能对话
    addDockWidget(Qt::RightDockWidgetArea, audioDock);
    addDockWidget(Qt::RightDockWidgetArea, analysisDock);
    addDockWidget(Qt::RightDockWidgetArea, chatDock);

    // 垂直排列右侧窗口（不使用tabify）
    splitDockWidget(audioDock, analysisDock, Qt::Vertical);
    splitDockWidget(analysisDock, chatDock, Qt::Vertical);

    // 设置角落区域，确保左侧和右侧区域独立
    setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
    setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
    setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
    setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);

    // 设置各Dock窗口的特性
    audioDock->setAllowedAreas(Qt::RightDockWidgetArea);
    analysisDock->setAllowedAreas(Qt::RightDockWidgetArea);
    chatDock->setAllowedAreas(Qt::RightDockWidgetArea);

    // Dock 可浮动、可移动
    audioDock->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable);
    analysisDock->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable);
    chatDock->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable);

    // 设置右侧窗口的最小宽度和高度
    m_audioWidget->setMinimumWidth(320);
    m_audioWidget->setMinimumHeight(220);

    m_analysisWidget->setMinimumWidth(320);
    m_analysisWidget->setMinimumHeight(220);

    m_chatWidget->setMinimumWidth(320);
    m_chatWidget->setMinimumHeight(220);

    // 初始状态下隐藏所有Dock窗口，只展示可视化界面
    audioDock->hide();
    analysisDock->hide();
    chatDock->hide();
}

// 修改设备监控面板连接和初始化方法
void MainWindow::setupDeviceMonitorConnections() {
    // 连接设备监控面板的信号
    connect(m_deviceMonitorPanel, &DeviceMonitorPanel::deviceStatusClicked,
            this, &MainWindow::onDeviceStatusClicked);

    // 连接设备选择复选框的信号
    connect(m_eegCheckBox, &QCheckBox::toggled, this, &MainWindow::updateDeviceStatus);
    connect(m_ecgCheckBox, &QCheckBox::toggled, this, &MainWindow::updateDeviceStatus);
    connect(m_gsrCheckBox, &QCheckBox::toggled, this, &MainWindow::updateDeviceStatus);

    // 设置设备监控面板的字体，确保与应用程序其他部分一致
    QFont standardFont("Microsoft YaHei", 10);
    m_deviceMonitorPanel->setFont(standardFont);

    // 确保EEG、ECG、GSR标签使用统一字体
    m_deviceMonitorPanel->setDeviceLabelsFont(standardFont);

    // 初始化设备状态
    updateDeviceStatus();
}


void MainWindow::onDeviceStatusClicked(const QString &deviceName) {
    QString message = QString("点击了 %1 设备状态指示器").arg(deviceName);
    statusBar()->showMessage(message, 3000);

    // 可以在这里添加更多的设备状态点击处理逻辑
    // 例如显示设备详细信息对话框等
    qDebug() << "设备状态点击:" << deviceName;
}

void MainWindow::updateCurrentSubjectLabel() {
    int currentSubjectId = m_db->getCurrentSubjectId();

    if (currentSubjectId <= 0) {
        m_currentSubjectLabel->setText("当前被试：无");
        return;
    }

    // 查询当前被试信息 - 使用m_db成员变量的连接
    QSqlQuery query(m_db->getDatabase());
    query.prepare("SELECT name FROM subjects WHERE id = ?");
    query.addBindValue(currentSubjectId);

    if (query.exec() && query.next()) {
        QString name = query.value(0).toString();
        m_currentSubjectLabel->setText(QString("当前被试：%1").arg(name));
    } else {
        m_currentSubjectLabel->setText(QString("当前被试：ID %1").arg(currentSubjectId));
        qWarning() << "查询被试信息失败:" << query.lastError().text();
    }
}

void MainWindow::connectSignals() {
    // 连接设备控制按钮信号
    connect(m_connectButton, &QPushButton::clicked, this, &MainWindow::onConnectDevices);
    connect(m_disconnectButton, &QPushButton::clicked, this, &MainWindow::onDisconnectDevices);
    connect(m_startAcquisitionButton, &QPushButton::clicked, this, &MainWindow::onStartAcquisition);
    connect(m_stopAcquisitionButton, &QPushButton::clicked, this, &MainWindow::onStopAcquisition);

    // 连接刺激控制按钮信号
    connect(m_audioWidget, &AudioPlayerWidget::stimulusStateChanged,
            this, &MainWindow::onStimulusStateChanged);
    connect(m_audioWidget, &AudioPlayerWidget::stimulusProgressChanged,
            this, &MainWindow::onStimulusProgressChanged);
    connect(m_audioWidget, &AudioPlayerWidget::audioEvent,
            this, &MainWindow::onAudioEvent);
    // 连接新增被试按钮信号
    connect(m_newSubjectButton, &QPushButton::clicked, this, &MainWindow::onNewSubject);

    // 连接选择被试按钮信号
    connect(m_selectSubjectButton, &QPushButton::clicked, this, &MainWindow::onSelectSubject);

    // 连接被试信息采集对话框的信号
    connect(m_subjectInfoDialog, &SubjectInfoDialog::subjectInfoCollected,
            this, &MainWindow::onSubjectInfoCollected);

    connect(m_chatWidget, &ChatWidget::switchToInterventionModule,
            this, &MainWindow::onSwitchToInterventionModule);
    // 连接ECG设备信号
    // ECG设备信号 - 使用Qt::QueuedConnection确保跨线程安全
    connect(m_ecgDevice, &ECGDevice::allChannelsDataReady,
            this, [this](const QVector<double>& data, qint64 timestamp) {
                // 将数据插入数据库
                m_db->insertEcgData(data, -1, timestamp);

                // 更新图表
                m_chartWidget->appendEcgData(data, timestamp);
            }, Qt::QueuedConnection);
    // 连接EEG设备信号
    if (m_eegDevice) {
        // 连接设备状态信号
        connect(m_eegDevice, &BioSignalDevice::connectionStatusChanged,
                this, &MainWindow::onDeviceConnectionStatusChanged);
        connect(m_eegDevice, &BioSignalDevice::acquisitionStatusChanged,
                this, &MainWindow::onDeviceAcquisitionStatusChanged);
        connect(m_eegDevice, &BioSignalDevice::errorOccurred,
                this, &MainWindow::onDeviceErrorOccurred);

        // 连接数据信号
        connect(m_eegDevice, &BioSignalDevice::dataReady,
                [this](const QVector<double>& data, int channelIndex) {
                    // 单个数据点处理
                    if (data.size() >= 3) {
                        qint64 timestamp = QDateTime::currentMSecsSinceEpoch();
                        m_chartWidget->appendEegData(data[0], data[1], data[2], timestamp);
                        m_db->insertEegData(data[0], data[1], data[2], timestamp);
                    }
                });

        connect(m_eegDevice, &BioSignalDevice::allChannelsDataReady,
                [this](const QVector<double>& allData) {
                    // 确保数据大小正确
                    if (allData.size() == 3) {
                        qint64 timestamp = QDateTime::currentMSecsSinceEpoch();
                        m_chartWidget->appendEegData(allData[0], allData[1], allData[2], timestamp);
                        m_db->insertEegData(allData[0], allData[1], allData[2], timestamp);

                        // 调试输出
                        qDebug() << "接收到所有EEG通道数据:" << allData;
                    }
                });
    }

    // 连接GSR设备信号
    if (m_gsrDevice) {
        // 连接状态信号
        connect(m_gsrDevice, &BioSignalDevice::connectionStatusChanged,
                this, &MainWindow::onDeviceConnectionStatusChanged);
        connect(m_gsrDevice, &BioSignalDevice::acquisitionStatusChanged,
                this, &MainWindow::onDeviceAcquisitionStatusChanged,
                Qt::QueuedConnection);
        connect(m_gsrDevice, &BioSignalDevice::errorOccurred,
                this, &MainWindow::onDeviceErrorOccurred);

        // 数据信号
        connect(m_gsrDevice, &BioSignalDevice::dataReady,
                [this](const QVector<double>& data, int channelIndex) {
                    // 检查是否是GSR特殊通道数据
                    if (channelIndex == -2 && data.size() >= 2) {
                        // 这是GSR数据，使用特定格式处理
                        m_chartWidget->appendGsrData(data[0], data[1],
                                                     QDateTime::currentMSecsSinceEpoch());
                        m_db->insertGsrData(data[0], data[1],
                                            QDateTime::currentMSecsSinceEpoch());

                        // 调试输出
                        qDebug() << "接收到GSR数据:" << data;
                    }
                    else if (channelIndex >= 0 && channelIndex < 6) {
                        // 这是常规通道数据，可以按需处理
                        qDebug() << "接收到GSR通道" << channelIndex << "数据:" << data;
                    }
                });

        // 所有通道数据一次性处理
        connect(m_gsrDevice, &BioSignalDevice::allChannelsDataReady,
                [this](const QVector<double>& allData) {
                    // 确保数据大小正确
                    if (allData.size() >= 6) {
                        // 可以在这里添加对所有通道数据的处理逻辑
                        qDebug() << "接收到所有GSR通道数据:" << allData;
                    }
                });
    }

    // ChatWidget 发送用户提问，DatabaseManager 记录事件
    connect(m_chatWidget, &ChatWidget::userQuestionAsked,
            [this](const QString &question) {
                m_db->logChatEvent(question, "user");
            });

    // AudioPlayerWidget 开始/结束播放，记录事件
    connect(m_audioWidget, &AudioPlayerWidget::audioEvent,
            m_db, &DatabaseManager::logAudioEvent);
    // AnalysisWidget 启动训练和推理，记录事件
    connect(m_analysisWidget, &AnalysisWidget::trainingStarted,
            m_db, &DatabaseManager::logAnalysisEvent);
    connect(m_analysisWidget, &AnalysisWidget::inferenceStarted,
            m_db, &DatabaseManager::logAnalysisEvent);
    connect(m_processCSVButton, &QPushButton::clicked, this, &MainWindow::onProcessCSVFile);

    if (m_eegDevice) {
        connect(m_eegDevice, &EEGDevice::csvProcessingProgress,
                this, &MainWindow::onCSVProcessingProgress);
        connect(m_eegDevice, &EEGDevice::csvProcessingFinished,
                this, &MainWindow::onCSVProcessingFinished);
    }
}

// 处理音频事件
void MainWindow::onAudioEvent(const QString &event, qint64 timestamp) {
    // 记录到数据库
    m_db->logAudioEvent(event, timestamp);

    // 根据事件类型更新状态栏
    if (event == "stimulus_start") {
        statusBar()->showMessage("刺激已开始");
    } else if (event == "stimulus_stop") {
        statusBar()->showMessage("刺激已停止");
    } else if (event == "rest_start") {
        statusBar()->showMessage("静息阶段开始");
    } else if (event == "rest_end") {
        statusBar()->showMessage("静息阶段结束");
    }
}

// 处理刺激状态变化
void MainWindow::onStimulusStateChanged(StimulusState state) {
    // 根据状态更新UI
    switch (state) {
    case StimulusState::Idle:
        m_stimulusProgressBar->setValue(0);
        m_stimulusProgressBar->setFormat("未刺激");  // 空闲状态显示"未刺激"
        m_startStimulusButton->setEnabled(true);
        m_stopStimulusButton->setEnabled(false);
        break;
    case StimulusState::Stimulating:
        m_stimulusProgressBar->setStyleSheet("QProgressBar::chunk { background-color: #e74c3c; }"); // 红色
        m_stimulusProgressBar->setFormat("剩余: %v s");  // 刺激状态显示"剩余: xx s"
        m_startStimulusButton->setEnabled(false);
        m_stopStimulusButton->setEnabled(true);
        break;
    case StimulusState::Resting:
        m_stimulusProgressBar->setStyleSheet("QProgressBar::chunk { background-color: #3498db; }"); // 蓝色
        m_stimulusProgressBar->setFormat("剩余: %v s");  // 休息状态也显示"剩余: xx s"
        break;
    }
}

// 处理刺激进度变化
void MainWindow::onStimulusProgressChanged(int progress) {
    // 更新进度条
    m_stimulusProgressBar->setValue(progress);

    // 计算并更新剩余时间
    if (m_audioWidget->getStimulusState() != StimulusState::Idle) {
        // 获取总时间和已用时间的百分比
        int totalSeconds = 0;
        if (m_audioWidget->getStimulusState() == StimulusState::Stimulating) {
            totalSeconds = m_audioWidget->getStimulusDuration();
        } else {
            totalSeconds = m_audioWidget->getRestDuration();
        }

        // 计算剩余时间
        int remainingSeconds = totalSeconds * (100 - progress) / 100;

        // 更新进度条文本
        m_stimulusProgressBar->setFormat(QString("剩余: %1 s").arg(remainingSeconds));
    } else {
        m_stimulusProgressBar->setFormat("未刺激");
    }
}

void MainWindow::onSwitchToInterventionModule() {
    // 获取当前模式
    bool isInterventionMode = m_chatWidget->isInterventionMode();

    if (isInterventionMode) {
        // 已切换到智能干预模式
        statusBar()->showMessage("已切换到智能干预模式");
    } else {
        // 已切换回智能对话模式
        statusBar()->showMessage("已切换到智能对话模式");
    }
}

// 实现显示被试信息采集对话框的方法
void MainWindow::showSubjectInfoDialog() {
    // 显示被试信息采集对话框
    if (m_subjectInfoDialog->exec() == QDialog::Rejected) {
        // 如果用户取消了对话框，则显示主窗口
        show();
    }
}

void MainWindow::showSelectSubjectDialog() {
    // 创建对话框
    QDialog dialog(this);
    dialog.setWindowTitle("选择被试");
    dialog.setMinimumWidth(400);

    // 创建布局
    QVBoxLayout *layout = new QVBoxLayout(&dialog);

    // 创建列表控件
    QListWidget *subjectList = new QListWidget(&dialog);
    layout->addWidget(subjectList);

    // 获取所有被试信息
    QList<QVariantList> subjects = m_db->getAllSubjects();

    // 填充列表
    for (const QVariantList &subject : subjects) {
        int id = subject[0].toInt();
        QString name = subject[1].toString();
        QString gender = subject[2].toString();
        int age = subject[3].toInt();

        QString displayText = QString("ID: %1 - %2 (%3, %4岁)").arg(id).arg(name).arg(gender).arg(age);
        QListWidgetItem *item = new QListWidgetItem(displayText);
        item->setData(Qt::UserRole, id); // 存储被试ID
        subjectList->addItem(item);
    }

    // 创建按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    QPushButton *selectButton = new QPushButton("选择", &dialog);
    QPushButton *cancelButton = new QPushButton("取消", &dialog);

    buttonLayout->addWidget(selectButton);
    buttonLayout->addWidget(cancelButton);
    layout->addLayout(buttonLayout);

    // 连接按钮信号
    connect(cancelButton, &QPushButton::clicked, &dialog, &QDialog::reject);
    connect(selectButton, &QPushButton::clicked, [&]() {
        QListWidgetItem *currentItem = subjectList->currentItem();
        if (currentItem) {
            int subjectId = currentItem->data(Qt::UserRole).toInt();
            // 修正方法名：setCurrentSubject -> setCurrentSubjectId
            m_db->setCurrentSubjectId(subjectId);
            dialog.accept();

            // 更新状态栏
            QString subjectName = subjects[subjectList->currentRow()][1].toString();
            statusBar()->showMessage(QString("已选择被试: %1 (ID: %2)").arg(subjectName).arg(subjectId));

            // 更新当前被试标签
            updateCurrentSubjectLabel();
        } else {
            QMessageBox::warning(&dialog, "警告", "请先选择一个被试");
        }
    });

    // 执行对话框
    dialog.exec();
}

void MainWindow::onSubjectInfoCollected(int subjectId) {
    // 被试信息采集完成后，显示主窗口
    show();

    // 更新状态栏
    statusBar()->showMessage("被试信息采集完成，ID: " + QString::number(subjectId));

    // 更新当前被试标签
    updateCurrentSubjectLabel();
}

// 处理新增被试的槽函数
void MainWindow::onNewSubject() {
    // 显示被试信息采集对话框
    m_subjectInfoDialog->exec();
}

// 处理选择被试的槽函数
void MainWindow::onSelectSubject() {
    // 显示选择被试对话框
    showSelectSubjectDialog();
}

// 显示音频刺激设置对话框
void MainWindow::showAudioSettings() {
    // 直接调用 AudioPlayerWidget 的方法
    m_audioWidget->showAudioSettings();
}

// 显示算法分析设置对话框
void MainWindow::showAnalysisSettings() {
    // 显示算法分析设置对话框
    QDialog dialog(this);
    dialog.setWindowTitle("算法分析设置");
    dialog.setMinimumWidth(600);
    dialog.setMinimumHeight(450);

    // 设置统一的字体样式
    QFont standardFont("Microsoft YaHei", 10);
    dialog.setFont(standardFont);

    // 创建布局
    QVBoxLayout *mainLayout = new QVBoxLayout(&dialog);

    // 创建算法选择组
    QGroupBox *algorithmGroup = new QGroupBox("算法选择", &dialog);
    algorithmGroup->setFont(standardFont);
    QVBoxLayout *algorithmLayout = new QVBoxLayout(algorithmGroup);

    QRadioButton *fftRadio = new QRadioButton("快速傅里叶变换 (FFT)", algorithmGroup);
    QRadioButton *waveletRadio = new QRadioButton("小波变换", algorithmGroup);
    QRadioButton *mlRadio = new QRadioButton("机器学习模型", algorithmGroup);
    QRadioButton *deepRadio = new QRadioButton("深度学习模型", algorithmGroup);

    // 设置统一字体
    fftRadio->setFont(standardFont);
    waveletRadio->setFont(standardFont);
    mlRadio->setFont(standardFont);
    deepRadio->setFont(standardFont);

    // 默认选择FFT
    fftRadio->setChecked(true);

    algorithmLayout->addWidget(fftRadio);
    algorithmLayout->addWidget(waveletRadio);
    algorithmLayout->addWidget(mlRadio);
    algorithmLayout->addWidget(deepRadio);

    mainLayout->addWidget(algorithmGroup);

    // 创建参数设置组
    QTabWidget *paramsTabWidget = new QTabWidget(&dialog);
    paramsTabWidget->setFont(standardFont);

    // FFT参数选项卡
    QWidget *fftTab = new QWidget(paramsTabWidget);
    QGridLayout *fftLayout = new QGridLayout(fftTab);

    QLabel *windowSizeLabel = new QLabel("窗口大小:", fftTab);
    windowSizeLabel->setFont(standardFont);
    QComboBox *windowSizeCombo = new QComboBox(fftTab);
    windowSizeCombo->setFont(standardFont);
    windowSizeCombo->addItem("256", 256);
    windowSizeCombo->addItem("512", 512);
    windowSizeCombo->addItem("1024", 1024);
    windowSizeCombo->addItem("2048", 2048);
    windowSizeCombo->setCurrentIndex(2); // 默认1024

    QLabel *windowTypeLabel = new QLabel("窗口类型:", fftTab);
    windowTypeLabel->setFont(standardFont);
    QComboBox *windowTypeCombo = new QComboBox(fftTab);
    windowTypeCombo->setFont(standardFont);
    windowTypeCombo->addItem("汉宁窗(Hanning)");
    windowTypeCombo->addItem("汉明窗(Hamming)");
    windowTypeCombo->addItem("布莱克曼窗(Blackman)");
    windowTypeCombo->addItem("矩形窗(Rectangle)");

    QLabel *overlapLabel = new QLabel("重叠率(%):", fftTab);
    overlapLabel->setFont(standardFont);
    QSpinBox *overlapSpin = new QSpinBox(fftTab);
    overlapSpin->setFont(standardFont);
    overlapSpin->setRange(0, 90);
    overlapSpin->setValue(50);
    overlapSpin->setSingleStep(10);

    fftLayout->addWidget(windowSizeLabel, 0, 0);
    fftLayout->addWidget(windowSizeCombo, 0, 1);
    fftLayout->addWidget(windowTypeLabel, 1, 0);
    fftLayout->addWidget(windowTypeCombo, 1, 1);
    fftLayout->addWidget(overlapLabel, 2, 0);
    fftLayout->addWidget(overlapSpin, 2, 1);
    fftLayout->setRowStretch(3, 1);

    // 小波变换参数选项卡
    QWidget *waveletTab = new QWidget(paramsTabWidget);
    QGridLayout *waveletLayout = new QGridLayout(waveletTab);

    QLabel *waveletTypeLabel = new QLabel("小波类型:", waveletTab);
    waveletTypeLabel->setFont(standardFont);
    QComboBox *waveletTypeCombo = new QComboBox(waveletTab);
    waveletTypeCombo->setFont(standardFont);
    waveletTypeCombo->addItem("Haar");
    waveletTypeCombo->addItem("Daubechies (db4)");
    waveletTypeCombo->addItem("Symlet (sym8)");
    waveletTypeCombo->addItem("Coiflet (coif3)");

    QLabel *decompositionLevelLabel = new QLabel("分解级别:", waveletTab);
    decompositionLevelLabel->setFont(standardFont);
    QSpinBox *decompositionLevelSpin = new QSpinBox(waveletTab);
    decompositionLevelSpin->setFont(standardFont);
    decompositionLevelSpin->setRange(1, 10);
    decompositionLevelSpin->setValue(5);

    waveletLayout->addWidget(waveletTypeLabel, 0, 0);
    waveletLayout->addWidget(waveletTypeCombo, 0, 1);
    waveletLayout->addWidget(decompositionLevelLabel, 1, 0);
    waveletLayout->addWidget(decompositionLevelSpin, 1, 1);
    waveletLayout->setRowStretch(2, 1);

    // 机器学习模型参数选项卡
    QWidget *mlTab = new QWidget(paramsTabWidget);
    QGridLayout *mlLayout = new QGridLayout(mlTab);

    QLabel *mlModelLabel = new QLabel("模型类型:", mlTab);
    mlModelLabel->setFont(standardFont);
    QComboBox *mlModelCombo = new QComboBox(mlTab);
    mlModelCombo->setFont(standardFont);
    mlModelCombo->addItem("支持向量机 (SVM)");
    mlModelCombo->addItem("随机森林 (Random Forest)");
    mlModelCombo->addItem("梯度提升树 (XGBoost)");
    mlModelCombo->addItem("K近邻 (KNN)");

    QLabel *featureSelectionLabel = new QLabel("特征选择:", mlTab);
    featureSelectionLabel->setFont(standardFont);
    QComboBox *featureSelectionCombo = new QComboBox(mlTab);
    featureSelectionCombo->setFont(standardFont);
    featureSelectionCombo->addItem("主成分分析 (PCA)");
    featureSelectionCombo->addItem("递归特征消除 (RFE)");
    featureSelectionCombo->addItem("L1正则化特征选择");
    featureSelectionCombo->addItem("不使用特征选择");

    QLabel *cvFoldsLabel = new QLabel("交叉验证折数:", mlTab);
    cvFoldsLabel->setFont(standardFont);
    QSpinBox *cvFoldsSpin = new QSpinBox(mlTab);
    cvFoldsSpin->setFont(standardFont);
    cvFoldsSpin->setRange(2, 10);
    cvFoldsSpin->setValue(5);

    mlLayout->addWidget(mlModelLabel, 0, 0);
    mlLayout->addWidget(mlModelCombo, 0, 1);
    mlLayout->addWidget(featureSelectionLabel, 1, 0);
    mlLayout->addWidget(featureSelectionCombo, 1, 1);
    mlLayout->addWidget(cvFoldsLabel, 2, 0);
    mlLayout->addWidget(cvFoldsSpin, 2, 1);
    mlLayout->setRowStretch(3, 1);

    // 深度学习模型参数选项卡
    QWidget *deepTab = new QWidget(paramsTabWidget);
    QGridLayout *deepLayout = new QGridLayout(deepTab);

    QLabel *deepModelLabel = new QLabel("模型架构:", deepTab);
    deepModelLabel->setFont(standardFont);
    QComboBox *deepModelCombo = new QComboBox(deepTab);
    deepModelCombo->setFont(standardFont);
    deepModelCombo->addItem("卷积神经网络 (CNN)");
    deepModelCombo->addItem("长短期记忆网络 (LSTM)");
    deepModelCombo->addItem("EEGNet");
    deepModelCombo->addItem("自定义架构");

    QLabel *batchSizeLabel = new QLabel("批量大小:", deepTab);
    batchSizeLabel->setFont(standardFont);
    QSpinBox *batchSizeSpin = new QSpinBox(deepTab);
    batchSizeSpin->setFont(standardFont);
    batchSizeSpin->setRange(1, 256);
    batchSizeSpin->setValue(32);
    batchSizeSpin->setSingleStep(8);

    QLabel *epochsLabel = new QLabel("训练轮数:", deepTab);
    epochsLabel->setFont(standardFont);
    QSpinBox *epochsSpin = new QSpinBox(deepTab);
    epochsSpin->setFont(standardFont);
    epochsSpin->setRange(1, 1000);
    epochsSpin->setValue(100);
    epochsSpin->setSingleStep(10);

    QLabel *learningRateLabel = new QLabel("学习率:", deepTab);
    learningRateLabel->setFont(standardFont);
    QDoubleSpinBox *learningRateSpin = new QDoubleSpinBox(deepTab);
    learningRateSpin->setFont(standardFont);
    learningRateSpin->setRange(0.0001, 0.1);
    learningRateSpin->setValue(0.001);
    learningRateSpin->setSingleStep(0.001);
    learningRateSpin->setDecimals(5);

    deepLayout->addWidget(deepModelLabel, 0, 0);
    deepLayout->addWidget(deepModelCombo, 0, 1);
    deepLayout->addWidget(batchSizeLabel, 1, 0);
    deepLayout->addWidget(batchSizeSpin, 1, 1);
    deepLayout->addWidget(epochsLabel, 2, 0);
    deepLayout->addWidget(epochsSpin, 2, 1);
    deepLayout->addWidget(learningRateLabel, 3, 0);
    deepLayout->addWidget(learningRateSpin, 3, 1);
    deepLayout->setRowStretch(4, 1);

    // 添加选项卡到选项卡控件
    paramsTabWidget->addTab(fftTab, "FFT参数");
    paramsTabWidget->addTab(waveletTab, "小波参数");
    paramsTabWidget->addTab(mlTab, "机器学习参数");
    paramsTabWidget->addTab(deepTab, "深度学习参数");

    mainLayout->addWidget(paramsTabWidget);

    // 创建输出设置组
    QGroupBox *outputGroup = new QGroupBox("输出设置", &dialog);
    outputGroup->setFont(standardFont);
    QGridLayout *outputLayout = new QGridLayout(outputGroup);

    QCheckBox *saveResultsCheck = new QCheckBox("保存分析结果", outputGroup);
    saveResultsCheck->setFont(standardFont);
    saveResultsCheck->setChecked(true);

    QLabel *outputFormatLabel = new QLabel("输出格式:", outputGroup);
    outputFormatLabel->setFont(standardFont);
    QComboBox *outputFormatCombo = new QComboBox(outputGroup);
    outputFormatCombo->setFont(standardFont);
    outputFormatCombo->addItem("CSV");
    outputFormatCombo->addItem("JSON");
    outputFormatCombo->addItem("HDF5");
    outputFormatCombo->addItem("MAT (MATLAB)");

    QCheckBox *generateReportCheck = new QCheckBox("生成分析报告", outputGroup);
    generateReportCheck->setFont(standardFont);
    generateReportCheck->setChecked(true);

    outputLayout->addWidget(saveResultsCheck, 0, 0);
    outputLayout->addWidget(outputFormatLabel, 0, 1);
    outputLayout->addWidget(outputFormatCombo, 0, 2);
    outputLayout->addWidget(generateReportCheck, 1, 0, 1, 3);

    mainLayout->addWidget(outputGroup);

    // 创建按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    QPushButton *okButton = new QPushButton("确定", &dialog);
    okButton->setFont(standardFont);
    QPushButton *cancelButton = new QPushButton("取消", &dialog);
    cancelButton->setFont(standardFont);
    QPushButton *resetButton = new QPushButton("重置为默认", &dialog);
    resetButton->setFont(standardFont);

    buttonLayout->addWidget(resetButton);
    buttonLayout->addStretch();
    buttonLayout->addWidget(okButton);
    buttonLayout->addWidget(cancelButton);

    mainLayout->addLayout(buttonLayout);

    // 连接算法选择信号
    connect(fftRadio, &QRadioButton::toggled, [paramsTabWidget](bool checked) {
        if (checked) paramsTabWidget->setCurrentIndex(0);
    });
    connect(waveletRadio, &QRadioButton::toggled, [paramsTabWidget](bool checked) {
        if (checked) paramsTabWidget->setCurrentIndex(1);
    });
    connect(mlRadio, &QRadioButton::toggled, [paramsTabWidget](bool checked) {
        if (checked) paramsTabWidget->setCurrentIndex(2);
    });
    connect(deepRadio, &QRadioButton::toggled, [paramsTabWidget](bool checked) {
        if (checked) paramsTabWidget->setCurrentIndex(3);
    });

    // 连接按钮信号
    connect(cancelButton, &QPushButton::clicked, &dialog, &QDialog::reject);
    connect(resetButton, &QPushButton::clicked, [&]() {
        // 重置所有参数为默认值
        fftRadio->setChecked(true);
        windowSizeCombo->setCurrentIndex(2); // 1024
        windowTypeCombo->setCurrentIndex(0); // Hanning
        overlapSpin->setValue(50);
        waveletTypeCombo->setCurrentIndex(0); // Haar
        decompositionLevelSpin->setValue(5);
        mlModelCombo->setCurrentIndex(0); // SVM
        featureSelectionCombo->setCurrentIndex(0); // PCA
        cvFoldsSpin->setValue(5);
        deepModelCombo->setCurrentIndex(0); // CNN
        batchSizeSpin->setValue(32);
        epochsSpin->setValue(100);
        learningRateSpin->setValue(0.001);
        saveResultsCheck->setChecked(true);
        outputFormatCombo->setCurrentIndex(0); // CSV
        generateReportCheck->setChecked(true);
    });
    connect(okButton, &QPushButton::clicked, [&]() {
        // 应用设置到分析部件
        // 这里根据选择的算法和参数设置分析部件的属性
        if (fftRadio->isChecked()) {
            m_analysisWidget->setAnalysisMethod("FFT");
            m_analysisWidget->setFFTParameters(
                windowSizeCombo->currentData().toInt(),
                windowTypeCombo->currentText(),
                overlapSpin->value()
                );
        } else if (waveletRadio->isChecked()) {
            m_analysisWidget->setAnalysisMethod("Wavelet");
            m_analysisWidget->setWaveletParameters(
                waveletTypeCombo->currentText(),
                decompositionLevelSpin->value()
                );
        } else if (mlRadio->isChecked()) {
            m_analysisWidget->setAnalysisMethod("ML");
            m_analysisWidget->setMLParameters(
                mlModelCombo->currentText(),
                featureSelectionCombo->currentText(),
                cvFoldsSpin->value()
                );
        } else if (deepRadio->isChecked()) {
            m_analysisWidget->setAnalysisMethod("DL");
            m_analysisWidget->setDLParameters(
                deepModelCombo->currentText(),
                batchSizeSpin->value(),
                epochsSpin->value(),
                learningRateSpin->value()
                );
        }

        // 设置输出选项
        m_analysisWidget->setSaveResults(saveResultsCheck->isChecked());
        m_analysisWidget->setOutputFormat(outputFormatCombo->currentText());
        m_analysisWidget->setGenerateReport(generateReportCheck->isChecked());

        dialog.accept();
        statusBar()->showMessage("算法分析设置已更新", 3000);
    });

    // 显示对话框
    dialog.exec();
}

// 实现设备连接槽函数
void MainWindow::onConnectDevices() {
    bool anyConnected = false;

    // 首先更新设备选择状态
    updateDeviceStatus();

    // 修改：检查设备是否为nullptr
    if (m_eegCheckBox->isChecked() && m_eegDevice) {
        if (m_eegDevice->connect()) {
            anyConnected = true;
        }
    } else if (m_eegDevice) {
        m_eegDevice->disconnect();
    }

    if (m_ecgCheckBox->isChecked()) {
        if (m_ecgDevice->connect()) {
            anyConnected = true;
        }
    } else {
        m_ecgDevice->disconnect();
    }

    if (m_gsrCheckBox->isChecked() && m_gsrDevice) {
        m_gsrDevice->startScanAndConnect();
        // GSR设备连接是异步的，anyConnected 状态将通过 connectionStatusChanged 信号更新
    } else if (m_gsrDevice) {
        m_gsrDevice->disconnectDevice();
    }

    // 再次更新设备状态，确保UI反映最新状态
    updateDeviceStatus();

    // 根据当前已知的连接状态更新UI
    m_startAcquisitionButton->setEnabled(anyConnected);
    m_connectButton->setEnabled(true);

    // 更新断开设备按钮状态
    m_disconnectButton->setEnabled(anyConnected);

    if (anyConnected) {
        statusBar()->showMessage("设备已连接");
    }
}

void MainWindow::onDisconnectDevices() {
    bool allDisconnected = true;

    // 检查设备是否为nullptr并断开连接
    if (m_eegDevice && m_eegDevice->isConnected()) {
        if (!m_eegDevice->disconnect()) {
            allDisconnected = false;
        }
    }

    if (m_ecgDevice && m_ecgDevice->isConnected()) {
        if (!m_ecgDevice->disconnect()) {
            allDisconnected = false;
        }
    }

    if (m_gsrDevice && m_gsrDevice->isConnected()) {
        if (!m_gsrDevice->disconnectDevice()) {
            allDisconnected = false;
        }
    }

    // 更新设备状态
    updateDeviceStatus();

    // 更新UI状态
    m_startAcquisitionButton->setEnabled(false);
    m_stopAcquisitionButton->setEnabled(false);
    m_disconnectButton->setEnabled(false);
    m_connectButton->setEnabled(true);

    if (allDisconnected) {
        statusBar()->showMessage("所有设备已断开连接");
    } else {
        statusBar()->showMessage("部分设备断开失败，请检查设备状态");
    }
}


// 修改 onStartAcquisition 方法中的 GSR 设备启动代码
bool MainWindow::onStartAcquisition() {
    bool anyStarted = false;

    // 修改：检查设备是否为nullptr
    if (m_eegCheckBox->isChecked() && m_eegDevice && m_eegDevice->isConnected()) {
        if (m_eegDevice->startAcquisition()) {
            anyStarted = true;
        }
    }

    if (m_ecgCheckBox->isChecked() && m_ecgDevice->isConnected()) {
        if (m_ecgDevice->startAcquisition()) {
            anyStarted = true;
        }
    }

    if (m_gsrCheckBox->isChecked() && m_gsrDevice && m_gsrDevice->isConnected()) {
        // 修改：使用直接调用并创建一个信号连接来处理结果，而不是尝试获取返回值
        QMetaObject::invokeMethod(m_gsrDevice, "startAcquisition", Qt::QueuedConnection);

        // 假设设备连接成功，就认为采集可以开始
        // 实际状态将通过 acquisitionStatusChanged 信号更新
        anyStarted = true;
    }

    if (anyStarted) {
        m_startAcquisitionButton->setEnabled(false);
        m_stopAcquisitionButton->setEnabled(true);
        m_connectButton->setEnabled(false);
        statusBar()->showMessage("数据采集已开始");
    }

    return anyStarted;
}

// 实现停止采集槽函数
void MainWindow::onStopAcquisition() {
    if (m_eegDevice && m_eegDevice->isAcquiring()) {
        m_eegDevice->stopAcquisition();
    }

    if (m_ecgDevice->isAcquiring()) {
        m_ecgDevice->stopAcquisition();
    }

    if (m_gsrDevice && m_gsrDevice->isAcquiring()) {
        // 修改：使用 QMetaObject::invokeMethod 正确调用 GSR 设备的 stopAcquisition 方法
        // 不尝试获取返回值
        QMetaObject::invokeMethod(m_gsrDevice, "stopAcquisition", Qt::QueuedConnection);
    }

    m_startAcquisitionButton->setEnabled(true);
    m_stopAcquisitionButton->setEnabled(false);
    m_connectButton->setEnabled(true);
    statusBar()->showMessage("数据采集已停止");
}

// 实现设备连接状态变化槽函数
// 修改设备连接状态变化方法，确保在状态变化时更新指示器
void MainWindow::onDeviceConnectionStatusChanged(bool connected) {
    // 获取发送信号的设备
    BioSignalDevice *device = qobject_cast<BioSignalDevice*>(sender());

    // 更新对应设备的监控面板状态
    if (device == m_eegDevice) {
        if (connected) {
            m_deviceMonitorPanel->setEEGStatus(StatusIndicator::Connected);
        } else if (m_eegCheckBox->isChecked()) {
            m_deviceMonitorPanel->setEEGStatus(StatusIndicator::Selected);
        } else {
            m_deviceMonitorPanel->setEEGStatus(StatusIndicator::NotSelected);
        }
    } else if (device == m_ecgDevice) {
        if (connected) {
            m_deviceMonitorPanel->setECGStatus(StatusIndicator::Connected);
        } else if (m_ecgCheckBox->isChecked()) {
            m_deviceMonitorPanel->setECGStatus(StatusIndicator::Selected);
        } else {
            m_deviceMonitorPanel->setECGStatus(StatusIndicator::NotSelected);
        }
    } else if (device == m_gsrDevice) {
        if (connected) {
            m_deviceMonitorPanel->setGSRStatus(StatusIndicator::Connected);
        } else if (m_gsrCheckBox->isChecked()) {
            m_deviceMonitorPanel->setGSRStatus(StatusIndicator::Selected);
        } else {
            m_deviceMonitorPanel->setGSRStatus(StatusIndicator::NotSelected);
        }
    }

    // 更新UI状态
    // 修改：检查设备是否为nullptr
    bool anyConnected = (m_eegDevice && m_eegDevice->isConnected()) ||
                        m_ecgDevice->isConnected() ||
                        (m_gsrDevice && m_gsrDevice->isConnected());

    m_startAcquisitionButton->setEnabled(anyConnected);

    // 更新断开设备按钮状态
    m_disconnectButton->setEnabled(anyConnected);

    // 更新状态栏
    if (connected) {
        statusBar()->showMessage("设备已连接");
    } else if (!anyConnected) {
        statusBar()->showMessage("所有设备已断开连接");
    }

    // 打印当前所有设备状态
    qDebug() << "当前设备状态:";
    if (m_eegDevice) qDebug() << "EEG设备:" << (m_eegDevice->isConnected() ? "已连接" : "未连接");
    qDebug() << "ECG设备:" << (m_ecgDevice->isConnected() ? "已连接" : "未连接");
    if (m_gsrDevice) qDebug() << "GSR设备:" << (m_gsrDevice->isConnected() ? "已连接" : "未连接");
}


// 实现设备采集状态变化槽函数
void MainWindow::onDeviceAcquisitionStatusChanged(bool acquiring) {
    // 获取发送信号的设备
    BioSignalDevice *device = qobject_cast<BioSignalDevice*>(sender());

    // 根据设备类型和采集状态更新监控面板
    if (device == m_eegDevice) {
        if (acquiring) {
            m_deviceMonitorPanel->setEEGStatus(StatusIndicator::Working, 0.85);
        } else if (m_eegDevice->isConnected()) {
            m_deviceMonitorPanel->setEEGStatus(StatusIndicator::Connected);
        } else if (m_eegCheckBox->isChecked()) {
            m_deviceMonitorPanel->setEEGStatus(StatusIndicator::Selected);
        } else {
            m_deviceMonitorPanel->setEEGStatus(StatusIndicator::NotSelected);
        }
    } else if (device == m_ecgDevice) {
        if (acquiring) {
            m_deviceMonitorPanel->setECGStatus(StatusIndicator::Working, 0.90);
        } else if (m_ecgDevice->isConnected()) {
            m_deviceMonitorPanel->setECGStatus(StatusIndicator::Connected);
        } else if (m_ecgCheckBox->isChecked()) {
            m_deviceMonitorPanel->setECGStatus(StatusIndicator::Selected);
        } else {
            m_deviceMonitorPanel->setECGStatus(StatusIndicator::NotSelected);
        }
    } else if (device == m_gsrDevice) {
        if (acquiring) {
            m_deviceMonitorPanel->setGSRStatus(StatusIndicator::Working, 0.80);
        } else if (m_gsrDevice->isConnected()) {
            m_deviceMonitorPanel->setGSRStatus(StatusIndicator::Connected);
        } else if (m_gsrCheckBox->isChecked()) {
            m_deviceMonitorPanel->setGSRStatus(StatusIndicator::Selected);
        } else {
            m_deviceMonitorPanel->setGSRStatus(StatusIndicator::NotSelected);
        }
    }

    // 更新UI状态
    // 修改：检查设备是否为nullptr
    bool anyAcquiring = (m_eegDevice && m_eegDevice->isAcquiring()) ||
                        m_ecgDevice->isAcquiring() ||
                        (m_gsrDevice && m_gsrDevice->isAcquiring());

    m_startAcquisitionButton->setEnabled(!anyAcquiring);
    m_stopAcquisitionButton->setEnabled(anyAcquiring);
    m_connectButton->setEnabled(!anyAcquiring);

    // 更新状态栏
    if (acquiring) {
        statusBar()->showMessage("数据采集中...");
    } else if (!anyAcquiring) {
        statusBar()->showMessage("数据采集已停止");
    }
}

// 实现设备错误处理槽函数
void MainWindow::onDeviceErrorOccurred(const QString &errorMessage) {
    // 在状态栏显示错误
    statusBar()->showMessage("错误: " + errorMessage, 5000);

    // 显示错误对话框
    QMessageBox::warning(this, "设备错误", errorMessage);

    // 获取发送错误信号的设备，并更新对应的监控面板状态
    BioSignalDevice *device = qobject_cast<BioSignalDevice*>(sender());
    if (device == m_eegDevice && m_eegCheckBox->isChecked()) {
        m_deviceMonitorPanel->setEEGStatus(StatusIndicator::Selected);
    } else if (device == m_ecgDevice && m_ecgCheckBox->isChecked()) {
        m_deviceMonitorPanel->setECGStatus(StatusIndicator::Selected);
    } else if (device == m_gsrDevice && m_gsrCheckBox->isChecked()) {
        m_deviceMonitorPanel->setGSRStatus(StatusIndicator::Selected);
    }
}

void MainWindow::updateDeviceStatus() {
    // 根据复选框状态更新设备状态指示器
    if (m_eegCheckBox && m_eegCheckBox->isChecked()) {
        if (m_eegDevice && m_eegDevice->isConnected()) {
            m_deviceMonitorPanel->setEEGStatus(StatusIndicator::Connected);
        } else {
            m_deviceMonitorPanel->setEEGStatus(StatusIndicator::Selected);
        }
    } else {
        m_deviceMonitorPanel->setEEGStatus(StatusIndicator::NotSelected);
    }

    if (m_ecgCheckBox && m_ecgCheckBox->isChecked()) {
        if (m_ecgDevice && m_ecgDevice->isConnected()) {
            m_deviceMonitorPanel->setECGStatus(StatusIndicator::Connected);
        } else {
            m_deviceMonitorPanel->setECGStatus(StatusIndicator::Selected);
        }
    } else {
        m_deviceMonitorPanel->setECGStatus(StatusIndicator::NotSelected);
    }

    if (m_gsrCheckBox && m_gsrCheckBox->isChecked()) {
        if (m_gsrDevice && m_gsrDevice->isConnected()) {
            m_deviceMonitorPanel->setGSRStatus(StatusIndicator::Connected);
        } else {
            m_deviceMonitorPanel->setGSRStatus(StatusIndicator::Selected);
        }
    } else {
        m_deviceMonitorPanel->setGSRStatus(StatusIndicator::NotSelected);
    }
}

// ***** 新增：CSV处理相关槽函数实现 *****
void MainWindow::onProcessCSVFile()
{
    // 检查EEG设备是否可用
    if (!m_eegDevice) {
        QMessageBox::warning(this, "错误", "EEG设备未初始化，无法处理CSV文件");
        return;
    }

    // 选择输入CSV文件
    QString inputFilePath = QFileDialog::getOpenFileName(
        this,
        "选择原始EEG数据CSV文件",
        QDir::currentPath(),
        "CSV文件 (*.csv);;所有文件 (*.*)"
        );

    if (inputFilePath.isEmpty()) {
        return; // 用户取消了文件选择
    }

    // 验证输入文件是否存在
    if (!QFile::exists(inputFilePath)) {
        QMessageBox::warning(this, "错误", "选择的文件不存在: " + inputFilePath);
        return;
    }

    // 选择输出CSV文件
    QFileInfo inputInfo(inputFilePath);
    QString defaultOutputPath = inputInfo.absolutePath() + "/" +
                                inputInfo.baseName() + "_filtered.csv";

    QString outputFilePath = QFileDialog::getSaveFileName(
        this,
        "保存滤波后的CSV文件",
        defaultOutputPath,
        "CSV文件 (*.csv);;所有文件 (*.*)"
        );

    if (outputFilePath.isEmpty()) {
        return; // 用户取消了文件保存
    }

    // 确保输出文件有.csv扩展名
    if (!outputFilePath.endsWith(".csv", Qt::CaseInsensitive)) {
        outputFilePath += ".csv";
    }

    // 显示处理信息
    QString processingInfo = QString("开始处理CSV文件...\n输入文件: %1\n输出文件: %2")
                                 .arg(QFileInfo(inputFilePath).fileName())
                                 .arg(QFileInfo(outputFilePath).fileName());

    qDebug() << processingInfo;
    statusBar()->showMessage("正在处理CSV文件...");

    // 显示进度条和更新标签
    m_csvProgressLabel->setText("处理中...");
    m_csvProgressBar->setValue(0);
    m_csvProgressBar->setVisible(true);

    // 禁用处理按钮，防止重复处理
    m_processCSVButton->setEnabled(false);

    // 启动CSV文件处理（异步处理）
    // 使用QTimer::singleShot来避免阻塞UI线程
    QTimer::singleShot(100, [this, inputFilePath, outputFilePath]() {
        m_eegDevice->processCSVFile(inputFilePath, outputFilePath);
    });
}

void MainWindow::onCSVProcessingProgress(int percentage)
{
    m_csvProgressBar->setValue(percentage);

    QString progressText;
    if (percentage < 20) {
        progressText = "加载数据...";
    } else if (percentage < 40) {
        progressText = "验证格式...";
    } else if (percentage < 80) {
        progressText = "应用滤波...";
    } else if (percentage < 100) {
        progressText = "保存结果...";
    } else {
        progressText = "完成";
    }

    m_csvProgressLabel->setText(progressText);
    statusBar()->showMessage(QString("CSV处理进度: %1% - %2").arg(percentage).arg(progressText));
}

void MainWindow::onCSVProcessingFinished(bool success, const QString& message)
{
    // 隐藏进度条
    m_csvProgressBar->setVisible(false);
    m_csvProgressLabel->setText("就绪");

    // 重新启用处理按钮
    m_processCSVButton->setEnabled(true);

    if (success) {
        // 处理成功
        statusBar()->showMessage("CSV文件处理完成", 3000);

        QMessageBox::information(this, "处理完成", message);

        qDebug() << "CSV文件处理成功:" << message;
    } else {
        // 处理失败
        statusBar()->showMessage("CSV文件处理失败", 5000);

        QMessageBox::critical(this, "处理失败", message);

        qWarning() << "CSV文件处理失败:" << message;
    }
}

// 显示智能对话界面
void MainWindow::showChatDialog() {
    // 创建对话框
    QDialog dialog(this);
    dialog.setWindowTitle("智能对话");
    dialog.setMinimumWidth(800);
    dialog.setMinimumHeight(600);

    // 创建布局
    QVBoxLayout *layout = new QVBoxLayout(&dialog);

    // 将ChatWidget添加到对话框
    layout->addWidget(m_chatWidget);

    // 移除ChatWidget的父对象，以便在对话框关闭后不会被销毁
    connect(&dialog, &QDialog::finished, [this]() {
        m_chatWidget->setParent(nullptr);
    });

    // 显示对话框
    dialog.exec();
}

// 修改setupDeviceThreads方法
void MainWindow::setupDeviceThreads()
{
    // 创建ECG设备线程
    m_ecgThread = new ECGDeviceThread(m_ecgDevice, this);

    // 创建GSR设备线程
    m_gsrThread = new GSRDeviceThread(m_gsrDevice, this);

    // 启动线程
    m_ecgThread->start();
    m_gsrThread->start();

    // 连接线程完成信号
    connect(m_ecgThread, &QThread::finished, m_ecgThread, &QObject::deleteLater);
    connect(m_gsrThread, &QThread::finished, m_gsrThread, &QObject::deleteLater);
}
void MainWindow::onGSRSamplingRateChanged(QAction *action)
{
    if (!m_gsrDevice) {
        statusBar()->showMessage("GSR设备未初始化", 3000);
        return;
    }

    QString rateText = action->text();
    GSRDevice::SamplingRateOption rateOption;

    // 根据选择的文本确定采样率选项
    if (rateText == "100 Hz") {
        rateOption = GSRDevice::RATE_100HZ;
    } else if (rateText == "200 Hz") {
        rateOption = GSRDevice::RATE_200HZ;
    } else if (rateText == "400 Hz") {
        rateOption = GSRDevice::RATE_400HZ;
    } else if (rateText == "800 Hz") {
        rateOption = GSRDevice::RATE_800HZ;
    } else {
        statusBar()->showMessage("无效的采样率选项", 3000);
        return;
    }

    // 设置GSR设备采样率
    if (m_gsrDevice->setSamplingRate(rateOption)) {
        statusBar()->showMessage(QString("GSR采样率已设置为 %1").arg(rateText), 3000);
    } else {
        statusBar()->showMessage("设置GSR采样率失败", 3000);
    }
}

